package com.vince.tv.controller;

import com.vince.tv.entity.Category;
import com.vince.tv.entity.Movie;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/movies")
public class MovieController {

    @Autowired
    private MongoTemplate mongoTemplate;

    @GetMapping("/list/{categoryId}")
    public List<Movie> listMovie(@PathVariable String categoryId) {
        Category category = mongoTemplate.findById(categoryId, Category.class);

        if (category == null) {
            throw new RuntimeException("视频集不存在");
        }
        Query query = new Query(Criteria.where("category").is(category.getTitle()));
        List<Movie> list = mongoTemplate.find(query, Movie.class);
        // todo 分页
        list.stream().forEach(Movie::initM3u8Url);
        return list;
    }

    @GetMapping("/category/tree")
    public List<CategoryNode> getCategoryTree() {
        List<Category> categoryList = mongoTemplate.findAll(Category.class);
        categoryList = categoryList.stream()
                .filter(e -> e.getTitle().contains("-"))
                .filter(e -> e.getTitle().split("-").length == 3)
                .collect(Collectors.toList());

        List<CategoryNode> list = new ArrayList<>();

        categoryList.forEach(e -> {

            String baseStr = Base64.getEncoder().encodeToString(new String(e.getId() + "|" + e.getTitle()).getBytes());
            setNode(list, e.getTitle() + "|" + baseStr);
        });
        return list;
    }

    public void setNode(List<CategoryNode> categoryNodeList, String str) {
        if (!str.contains("-") && !str.contains("|")) {
            return;
        }
        if (str.contains("-")) {
            String[] splitStrArrays = splitStr(str, "-");
            Optional<CategoryNode> optional = getMatchNode(categoryNodeList, splitStrArrays);
            if (optional.isPresent()) {
                CategoryNode node = optional.get();
                List<CategoryNode> sonNode = node.getSonNodeList();
                setNode(sonNode, splitStrArrays[1]);
            } else {
                CategoryNode node = new CategoryNode();
                node.setName(splitStrArrays[0]);
                categoryNodeList.add(node);
                List<CategoryNode> sonNode = new ArrayList<>();
                node.setSonNodeList(sonNode);
                setNode(sonNode, splitStrArrays[1]);
            }
        } else if (str.contains("|")) {
            String[] spiltStrArrays = splitStr(str, "|");
            Optional<CategoryNode> optional = getMatchNode(categoryNodeList, spiltStrArrays);
            if (!optional.isPresent()) {
                CategoryNode node = new CategoryNode();
                node.setName(spiltStrArrays[0]);
                String[] idAndTitle = StringUtils.split(new String(Base64.getDecoder().decode(spiltStrArrays[1])),"|");
                node.setId(idAndTitle[0]);
                node.setPathName(idAndTitle[1]);
                categoryNodeList.add(node);
            }
        }
    }

    private Optional<CategoryNode> getMatchNode(List<CategoryNode> categoryNodeList, String[] spiltStrArrays) {
        return categoryNodeList.stream().filter(e -> e.getName().equals(spiltStrArrays[0])).findFirst();
    }

    private String[] splitStr(String str, String separator) {
        String a = str.substring(0, str.indexOf(separator));
        String b = str.substring(str.indexOf(separator) + 1);
        return new String[]{a, b};
    }

    @Data
    class CategoryNode {
        private String name;
        private List<CategoryNode> sonNodeList;
        private String id;
        private String pathName;
    }
}
